﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MedicareModel;
using MySql.Data.MySqlClient;

namespace MedicareDataAccess
{
    public class EMTDAO : DAOConnection
    {
        public static EMTDAO GetInstance()
        {
            return new EMTDAO();
        }

        public EMT getEMTByID(int idEMT)
        {
            MySqlCommand cm = DBGetCommand(string.Format("SELECT * FROM emts WHERE idEMT={0}", idEMT));
            MySqlDataReader dr = cm.ExecuteReader();
            if (!dr.Read())
            {
                cm.Connection.Close();
                return null;
            }

            EMT anEMT = new EMT();
            anEMT.idEMT = (int)dr["idEMT"];
            anEMT.status = (string)dr["status"];

            return anEMT; 
        }

        public List<EMT> getAllEMTs()
        {
            List<EMT> emts = new List<EMT>(); 
            MySqlCommand cm = DBGetCommand(string.Format("SELECT * FROM emts"));
            MySqlDataReader dr = cm.ExecuteReader();
            while (dr.Read())
            {
                EMT anEMT = new EMT();
                anEMT.idEMT = (int)dr["idEMT"];
                anEMT.status = (string)dr["status"];

                emts.Add(anEMT);
            }

            cm.Connection.Close();
            return emts; 
        }

        public EMT sendEMT()
        {
            string query = string.Format("INSERT INTO emts (status) VALUES ('Deployed');");
            MySqlCommand cm = DBGetCommand(query);
            cm.ExecuteNonQuery();

            MySqlCommand cm2 = DBGetCommand(string.Format("SELECT * FROM emts ORDER BY idEMT DESC LIMIT 1"));
            MySqlDataReader dr = cm2.ExecuteReader();
            if (!dr.Read())
            {
                cm2.Connection.Close();
                return null;
            }

            EMT output = getEMTByID((int)dr["idEMT"]);
            cm2.Connection.Close();
            return output;
        }
    }
}
